import 'dart:convert';
import 'dart:developer' as developer;
import 'package:flutter/services.dart';
import '../models/comic_chapter_model.dart';
import '../screens/home/model/comic_detail_model.dart';
import '../utils/http_helper.dart';

class ChapterManager {
  static const String _logTag = '[章节管理器]';

  List<ComicChaptersModel> _chapters = [];
  List<String> _allImages = [];
  List<int> _chapterStartIndices = [];
  List<int> _chapterImageCounts = [];
  List<int> _chapterRealIndices = [];

  int _currentChapterIndex = 0;
  int _displayChapterIndex = 0;
  String _currentChapterTitle = '';
  ComicDetailModel? _comicDetail; // 添加漫画详情信息

  // Getters
  List<ComicChaptersModel> get chapters => _chapters;
  List<String> get allImages => _allImages;
  List<int> get chapterStartIndices => _chapterStartIndices;
  List<int> get chapterImageCounts => _chapterImageCounts;
  List<int> get chapterRealIndices => _chapterRealIndices;

  int get currentChapterIndex => _currentChapterIndex;
  int get displayChapterIndex => _displayChapterIndex;
  String get currentChapterTitle => _currentChapterTitle;
  ComicDetailModel? get comicDetail => _comicDetail; // 添加漫画详情getter

  // 加载漫画详情
  Future<void> loadComicDetail(
      String initialChapterId, String seletedChapterId) async {
    // final String response = await rootBundle.loadString('assets/json/comin_detail.json');

    final userResponse = await HttpUtil().getModel<ComicDetailModel>(
      'Comic/GetComicDetail',
      params: {"comicId": initialChapterId},
      fromJson: (json) =>
          ComicDetailModel.fromJson(json as Map<String, dynamic>),
    );

    // if (userResponse?.status == 200 && userResponse?.result != null) {
    //   state = AsyncValue.data(userResponse!.result!);
    // } else {
    //   state = AsyncValue.error(
    //       'Failed to load comic details', StackTrace.current);
    // }
    //
    // final Map<String, dynamic> data = json.decode(response);

    if (userResponse?.status == 200 && userResponse?.result != null) {
      _comicDetail = userResponse!.result!; // 保存漫画详情
      _chapters = userResponse.result!.comicChapters ?? [];
      _currentChapterIndex = _chapters
          .indexWhere((chapter) => chapter.chapterId == seletedChapterId);
      if (_currentChapterIndex == -1) {
        _currentChapterIndex = 0;
      }
      _displayChapterIndex = _currentChapterIndex;
    }
  }

  // 加载指定章节的图片
  Future<(List<String>, int)> loadChapterImages(String? chapterId) async {
    if (chapterId == null) {
      developer.log('$_logTag loadChapterImages chapterId为空');
      return (<String>[], -1);
    }

    developer.log('$_logTag loadChapterImages 开始请求章节图片，chapterId: $chapterId');

    try {
      // final String response = await rootBundle.loadString('assets/json/$chapterId.json');
      // final Map<String, dynamic> data = json.decode(response);
      //
      // if (data['success'] == true && data['data'] != null) {
      //   final String urlString = data['data']['url'] ?? '';
      //   final List<String> imageUrls = urlString.split(',').where((url) => url.isNotEmpty).toList();
      //   return imageUrls;
      // }

      final response = await HttpUtil().getModel<ComicChapterModel>(
        'Comic/GetComicChapter',
        params: {'chapterId': chapterId},
        fromJson: (json) =>
            ComicChapterModel.fromJson(json as Map<String, dynamic>),
      );

      developer.log('$_logTag loadChapterImages HTTP请求完成');
      developer.log(
          '$_logTag loadChapterImages response?.status: ${response?.status}');
      developer.log(
          '$_logTag loadChapterImages response?.result != null: ${response?.result != null}');

      if (response?.status == 200 && response?.result != null) {
        final String urlString = response?.result?.url ?? '';
        developer.log('$_logTag loadChapterImages urlString: $urlString');
        developer
            .log('$_logTag loadChapterImages urlString长度: ${urlString.length}');

        final List<String> imageUrls =
            urlString.split(',').where((url) => url.isNotEmpty).toList();
        developer
            .log('$_logTag loadChapterImages 解析后图片数量: ${imageUrls.length}');

        if (imageUrls.isNotEmpty) {
          developer
              .log('$_logTag loadChapterImages 第一张图片URL: ${imageUrls.first}');
          developer
              .log('$_logTag loadChapterImages 最后一张图片URL: ${imageUrls.last}');
        }

        return (imageUrls, 200);
      } else {
        developer.log(
            '$_logTag loadChapterImages HTTP请求失败 - status: ${response?.status}, result为空: ${response?.result == null}');
        return (<String>[], response?.status ?? -10);
      }
    } catch (e) {
      developer.log('$_logTag loadChapterImages 请求异常: $e');
      return (<String>[], -1);
    }
  }

  // 加载单个章节（重新加载模式）
  Future<(bool, int)> loadSingleChapter(int chapterIndex) async {
    developer.log(
        '$_logTag loadSingleChapter 开始加载章节，索引: $chapterIndex，总章节数: ${_chapters.length}');

    if (chapterIndex < 0 || chapterIndex >= _chapters.length) {
      developer.log('$_logTag loadSingleChapter 章节索引无效: $chapterIndex');
      return (false, -1);
    }

    final chapter = _chapters[chapterIndex];
    final chapterId = chapter.chapterId;
    developer.log(
        '$_logTag loadSingleChapter 开始加载章节图片，chapterId: $chapterId，章节标题: ${chapter.chapterTitle}');

    final (imageUrls, code) = await loadChapterImages(chapterId);
    developer
        .log('$_logTag loadSingleChapter 章节图片加载完成，图片数量: ${imageUrls.length}');

    if (imageUrls.isNotEmpty) {
      _allImages = imageUrls;
      _chapterStartIndices = [0];
      _chapterImageCounts = [imageUrls.length];
      _chapterRealIndices = [chapterIndex];
      _currentChapterIndex = chapterIndex;
      _displayChapterIndex = chapterIndex;
      _currentChapterTitle = chapter.chapterTitle ?? '';

      developer.log('$_logTag loadSingleChapter 章节数据重置完成');
      developer.log(
          '$_logTag loadSingleChapter _allImages.length: ${_allImages.length}');
      developer.log(
          '$_logTag loadSingleChapter _chapterStartIndices: $_chapterStartIndices');
      developer.log(
          '$_logTag loadSingleChapter _chapterImageCounts: $_chapterImageCounts');
      developer.log(
          '$_logTag loadSingleChapter _chapterRealIndices: $_chapterRealIndices');

      return (true, code);
    }
    developer.log('$_logTag loadSingleChapter 章节图片列表为空');
    return (false, code);
  }

  // 加载下一章（追加模式）
  Future<bool> loadNextChapter() async {
    if (_currentChapterIndex >= _chapters.length - 1) {
      return false;
    }

    var nextChapterIndex = _currentChapterIndex + 1;
    while (nextChapterIndex < _chapters.length) {
      final chapter = _chapters[nextChapterIndex];
      final chapterId = chapter.chapterId;
      final (imageUrls, code) = await loadChapterImages(chapterId);

      if (imageUrls.isNotEmpty) {
        _chapterStartIndices.add(_allImages.length);
        _chapterImageCounts.add(imageUrls.length);
        _chapterRealIndices.add(nextChapterIndex);
        _allImages.addAll(imageUrls);
        _currentChapterIndex = nextChapterIndex;
        _currentChapterTitle = chapter.chapterTitle ?? '';
        return true;
      } else {
        nextChapterIndex++;
      }
    }
    return false;
  }

  // 下拉加载上一章（前置追加模式）
  Future<bool> loadPreviousChapter(int currentVisibleIndex) async {
    final prevChapterIndex = _displayChapterIndex - 1;

    if (prevChapterIndex < 0) {
      return false;
    }

    final chapter = _chapters[prevChapterIndex];
    final chapterId = chapter.chapterId;
    final (imageUrls, code) = await loadChapterImages(chapterId);

    if (imageUrls.isNotEmpty) {
      // 在列表前面插入新章节
      _allImages.insertAll(0, imageUrls);

      // 更新所有章节的起始索引
      for (int i = 0; i < _chapterStartIndices.length; i++) {
        _chapterStartIndices[i] += imageUrls.length;
      }

      // 在前面插入新章节的信息
      _chapterStartIndices.insert(0, 0);
      _chapterImageCounts.insert(0, imageUrls.length);
      _chapterRealIndices.insert(0, prevChapterIndex);

      return true;
    }
    return false;
  }

  // 根据图片索引找到对应的章节索引
  int findChapterIndexFromImageIndex(int imageIndex) {
    developer.log(
        '$_logTag findChapterIndexFromImageIndex 查找图片索引 $imageIndex 对应的章节');
    developer.log(
        '$_logTag findChapterIndexFromImageIndex _chapterStartIndices: $_chapterStartIndices');
    developer.log(
        '$_logTag findChapterIndexFromImageIndex _chapterRealIndices: $_chapterRealIndices');

    for (int i = _chapterStartIndices.length - 1; i >= 0; i--) {
      if (imageIndex >= _chapterStartIndices[i]) {
        if (i < _chapterRealIndices.length) {
          final result = _chapterRealIndices[i];
          developer.log(
              '$_logTag findChapterIndexFromImageIndex 图片索引 $imageIndex 属于章节: $result');
          return result;
        }
        break;
      }
    }
    developer.log(
        '$_logTag findChapterIndexFromImageIndex 未找到匹配的章节，返回默认: $_displayChapterIndex');
    return _displayChapterIndex;
  }

  // 获取当前章节内的图片位置信息
  Map<String, int> getCurrentChapterPosition(int visibleImageIndex) {
    if (_chapterStartIndices.isEmpty || _chapterImageCounts.isEmpty) {
      return {'imageInChapter': 1, 'totalInChapter': 1};
    }

    // 找到当前图片所在的章节
    int chapterIndex = 0;
    for (int i = _chapterStartIndices.length - 1; i >= 0; i--) {
      if (visibleImageIndex >= _chapterStartIndices[i]) {
        chapterIndex = i;
        break;
      }
    }

    final chapterStart = _chapterStartIndices[chapterIndex];
    final imageInChapter = visibleImageIndex - chapterStart + 1;
    final totalInChapter = _chapterImageCounts[chapterIndex];

    return {
      'imageInChapter': imageInChapter.clamp(1, totalInChapter),
      'totalInChapter': totalInChapter,
    };
  }

  // 计算章节内图片编号对应的全局索引
  int calculateGlobalIndex(int imageNumberInChapter, int visibleImageIndex) {
    if (_chapterStartIndices.isEmpty || _chapterImageCounts.isEmpty) {
      return -1;
    }

    // 找到当前显示的章节在数组中的索引
    int chapterIndex = 0;
    for (int i = _chapterStartIndices.length - 1; i >= 0; i--) {
      if (visibleImageIndex >= _chapterStartIndices[i]) {
        chapterIndex = i;
        break;
      }
    }

    final totalInChapter = _chapterImageCounts[chapterIndex];
    if (imageNumberInChapter < 1 || imageNumberInChapter > totalInChapter) {
      return -1;
    }

    final chapterStart = _chapterStartIndices[chapterIndex];
    return chapterStart + imageNumberInChapter - 1;
  }

  // 更新显示章节索引
  void updateDisplayChapterIndex(int newIndex) {
    _displayChapterIndex = newIndex;
  }
}
